import router from '@/router'
import store from '@/store'

const whiteLisr = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 判断是有token 如果有next 没有 判断是否在白名单内 是放行 否则 去登录页
  if (store.getters.token) {
    // 如果已经登录跳转到登录页面 那就直接到首页
    if (to.path === '/login') {
      next('/')
    } else {
      console.log(store.state.user)
      if (!store.state.user.user.userId) {
        const res = await store.dispatch('user/getInfo')
        console.log(res)
        // 添加过滤后的路由
        const routes = await store.dispatch('permission/filterRoutes', res.roles.menus)
        // 添加路由
        // 404 page must be placed at the end !!!
        // 添加完动态路由再匹配404
        router.addRoutes([...routes,
          { path: '*', redirect: '/404', hidden: true }])
        // 之前的路由匹配已经错过 所以再次跳 等于刷新
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    // 判断是否在白名单
    if (whiteLisr.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
